package org.joy;

import com.google.gson.Gson;

import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class OCISginedRequest {

    public static String tenancyid = "ocid1.tenancy.oc1..aaaaaaaamdypr7vjm7e6ftrjngh3a3ffyj63cftfh4giko37zlderg4tfnmq";
    public static String userid = "ocid1.user.oc1..aaaaaaaah24musimppesv3ucptkthgto4o6mowq5jktchtuhakopqvlae4pa";
    public static String fingerprint = "d7:33:6c:3b:fa:a0:e1:c6:bf:b0:0e:84:93:bb:6d:67";
    public static String rsa_priv_key="-----BEGIN PRIVATE KEY-----\n" +
            "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCfuAKtLq6IFkkI\n" +
            "mSyGhtrQW6IEhsNB5onu/We5UJ5t5wRDWyzMPV298MiDTZmQmwti/VhjSu1D0sBu\n" +
            "+qe+PXtOItegsvIUM5UgjV/gB/sFCU70anbSu/EIvdNwT2wguHa5Lrxhr1MwyJs8\n" +
            "DnZR7yNFxkw0dDWHnP8m01twP7vN5YJGYdX46W56dnyr0j0fzHPI34FjpTIqpUbJ\n" +
            "vgrr+fmvD0PwqRW0UwstI6WIxDoiQ1XKX1Uf6CBISH1xkze/gBh587glvEeBkb7X\n" +
            "4SlhSyOZekfkOrmw54DK9Zx7yIyH3BVDhlDFZSAcMme+u0LC2tNUCsyjoWhElL6z\n" +
            "hUnekd5NAgMBAAECggEAGtCvClprDQgIzPvCgPeFJzQrOG1TvO2yvMAouPEzGCqQ\n" +
            "Car2E3g+E9SoJXtSy/dr6vuz6j+7JAbvLfLBVOxHlm+9GgrRH9klMWjq7tcIKulM\n" +
            "KzbwqiLJrfkI1bNP6RJvRFn3YMMpyWf0wBmBffITTvSi+K+GCTWvlNopYOgiZMfe\n" +
            "TmbNjpTvvfQhi24/V/002beRYpilhKVPZWDDjeutXVyVIak9HGC4SZ3/oNggy4zD\n" +
            "TBRQGHeu7RKIT62o340vp2eF4j8rPrWv3a/1mxygkVWoKqldnRLj3jGcwQirgDvU\n" +
            "H/atCgL4p7gi2Fr5iGGeOoXXDH1rzIy99PBZGWy1IQKBgQDhz2eD6uFakENpCWTx\n" +
            "FgF3Zb44+dIcLeBwke318CZGvNrmx3nXrhAkrItG6pB6AlkCR6K9OaakfqNxduEj\n" +
            "lATHxCoX0HaOM9qzOg1x//a2W+ODkY3G6eSDfkB68ZeUuPgDBIxoCcAUm6yPHJFG\n" +
            "BGypFQxziyHcyQjJEohs8tw0uQKBgQC1Eo683KAjqzJ1zjgXkSrM8ugRhi9/TreS\n" +
            "8Fuol8ykhSIKsvuSrS2kiMc+4uPiqNMz9xPifx7+XUJdefyWkrCjFScCx0y3MGya\n" +
            "UuPbO2ZxPkgdZwtnSQMzQJ8Bgp6uCF/dBHFP50TYoCuDU9SORE00pJKuYfBzK39u\n" +
            "Le2rTICUNQKBgDYWigMNNeGNgLgeKfGdhchltITNQkjBrGsKaWdpmKGFByIUUdkZ\n" +
            "toAyXEImWWkAOvXS1uZgcswgEWJSSWdOQz7ee/6sTlmNjis0Ephl6WCQ7hRLvxwQ\n" +
            "Vk4w5Z0NVXOoQq/mXQNmon3NNC4rd5i/4o81nX/nqbrK5LHVIJyIJ7rxAoGBAISR\n" +
            "IpmY+VFD7HydTynJ6UkFaewyjqGpEvNsL979zCCDLAojQdYAHhOA5EbhPDBco8w+\n" +
            "z3sa0Kkvw//F6Kygltu/B8GcAkl4FXrixtlh4r1z+L42C/5BUSt72y3y4JPPo8ef\n" +
            "kgoK6reihFjwzgSectvgxVcQc0cOiIw06fVo3BYlAoGAQKv0K9kJ5IlrnG4TyLOe\n" +
            "OnYNtNxAvn4JOMbpBEVb/dHGhU3AsSK+k0Tkx+gJFZ94H8IrjzPkd+F2PS82INhV\n" +
            "EADg8EhXOAyyYredCKRsIAmZWBGY+cLgT1S0o5FxJvIx82IMwBIi8nMqB0yDWWC9\n" +
            "dBLW+/8xlKScI+AfrflQVz4=\n" +
            "-----END PRIVATE KEY-----";


    public static String regionid="ap-singapore-1";
    public static void main(String[] args) throws Exception {
        PosTSignatures();
    }

    public static void PosTSignatures() throws Exception{

        String  apiKeyId =String.format("%s/%s/%s",tenancyid, userid, fingerprint);

        String host= "objectstorage.ap-singapore-1.oraclecloud.com";

        String path = "/n/cnjxmruwj0jf/b/buckettest/actions/renameObject";
        String method = "POST";
        String currentDate = getCurrentDate();

        String contentype = "application/json";



        Map<String,String> content = new LinkedHashMap<>();
        content.put("sourceName","demo2");
        content.put("newName","newdemojoy");
//        content.put("srcObjIfMatchETag","*");
//        content.put("newObjIfMatchETag","*");
//        content.put("newObjIfNoneMatchETag","*");

        Gson gson = new Gson(); //创建Gson对象
        String contentstr =   gson.toJson(content);
        System.out.println(contentstr);

        String contentlength = Integer.toString(contentstr.getBytes(StandardCharsets.UTF_8).length);

        MessageDigest  messageDigest = MessageDigest.getInstance("SHA-256");
        byte[] hash = messageDigest.digest(contentstr.getBytes(StandardCharsets.UTF_8));
        String xcontentsha256 = Base64.getEncoder().encodeToString(hash);

        String requestTargetHeader = String.format("(request-target): %s %s", method.toLowerCase(), path);
        String dateHeader = String.format("date: %s", currentDate);
        String hostHeader = String.format("host: %s", host);
        String contentypeHeader = String.format("content-type: %s", contentype);
        String contentlengthheader = String.format("content-length: %s", contentlength);
        String xcontentsha256header = String.format("x-content-sha256: %s", xcontentsha256);
        String headers = "(request-target) date host x-content-sha256 content-type content-length";


        String[] header= { requestTargetHeader, dateHeader, hostHeader, xcontentsha256header, contentypeHeader, contentlengthheader};
        String signString = Arrays.stream(header).filter(string -> !string.isEmpty()).collect(Collectors.joining("\n"));
        System.out.println(signString);
        String base64EncodedSignature = signSHA256RSA(signString,rsa_priv_key);
        String Authorization  = String.format("Signature version=\"1\",keyId=\"%s\",algorithm=\"rsa-sha256\",headers=\"%s\",signature=\"%s\"",apiKeyId, headers, base64EncodedSignature);
        System.out.println(Authorization);

    }

    public static void PutSignatures() throws Exception{

        String  apiKeyId =String.format("%s/%s/%s",tenancyid, userid, fingerprint);

        String host= "objectstorage.ap-singapore-1.oraclecloud.com";

        String path = "/n/cnjxmruwj0jf/b/buckettest/o/demo3";
        String method = "PUT";
        String currentDate = getCurrentDate();
        InputStream input = DateDemo.class.getResourceAsStream("/data.json");
        byte[] data = input.readAllBytes();

        String contentlength = Integer.toString(data.length);



        String requestTargetHeader = String.format("(request-target): %s %s", method.toLowerCase(), path);
        String dateHeader = String.format("date: %s", currentDate);
        String hostHeader = String.format("host: %s", host);
        String contentlengthheader = String.format("content-length: %s", contentlength);
//        String xcontentsha256header = String.format("x-content-sha256: %s", xcontentsha256);
        String headers = "(request-target) date host content-length";


        String[] header= { requestTargetHeader,dateHeader , hostHeader,contentlengthheader};
        String signString = Arrays.stream(header).filter(string -> !string.isEmpty()).collect(Collectors.joining("\n"));
        System.out.println(signString);
        String base64EncodedSignature = signSHA256RSA(signString,rsa_priv_key);
        String Authorization  = String.format("Signature version=\"1\",keyId=\"%s\",algorithm=\"rsa-sha256\",headers=\"%s\",signature=\"%s\"",apiKeyId, headers, base64EncodedSignature);
        System.out.println(Authorization);

    }

    private static void GetSignatures() throws Exception {
        String  apiKeyId =String.format("%s/%s/%s",tenancyid, userid, fingerprint);
        String host= "objectstorage.ap-singapore-1.oraclecloud.com";
        String path = "/n/cnjxmruwj0jf/b/buckettest/o/demo";
        String method = "GET";
        String currentDate = getCurrentDate();

        String requestTargetHeader = String.format("(request-target): %s %s", method.toLowerCase(), path);
        String hostHeader = String.format("host: %s", host);
        String dateHeader = String.format("date: %s", currentDate);
        String headers = "(request-target) date host";
        String[] header= { requestTargetHeader,dateHeader , hostHeader};
        String signString = Arrays.stream(header).filter(string -> !string.isEmpty()).collect(Collectors.joining("\n"));
        System.out.println(signString);
        String base64EncodedSignature = signSHA256RSA(signString,rsa_priv_key);
        String Authorization  = String.format("Signature version=\"1\",keyId=\"%s\",algorithm=\"rsa-sha256\",headers=\"%s\",signature=\"%s\"",apiKeyId, headers, base64EncodedSignature);
        System.out.println(Authorization);
    }

    private static String getCurrentDate(){
        final Date currentTime = new Date();
        final SimpleDateFormat sdf =
                new SimpleDateFormat("EEE, d MMM yyyy hh:mm:ss z", Locale.ENGLISH);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        return sdf.format(currentTime);
    }
    private static String signSHA256RSA(String input, String strPk) throws Exception {
        // Remove markers and new line characters in private key
        String realPK = strPk.replaceAll("-----END PRIVATE KEY-----", "")
                .replaceAll("-----BEGIN PRIVATE KEY-----", "")
                .replaceAll("\n", "");

        byte[] b1 = Base64.getDecoder().decode(realPK);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(b1);
        KeyFactory kf = KeyFactory.getInstance("RSA");

        Signature privateSignature = Signature.getInstance("SHA256withRSA");
        privateSignature.initSign(kf.generatePrivate(spec));
        privateSignature.update(input.getBytes("UTF-8"));
        byte[] s = privateSignature.sign();
        return Base64.getEncoder().encodeToString(s);
    }
}
